package com.tjbank.cssys.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tjbank.cssys.domain.CkOutsourcingCompany;
import com.tjbank.cssys.domain.CkOutsourcingCompanyAcceptLevel;
import com.tjbank.cssys.domain.CkOutsourcingCompanyRate;
import com.tjbank.cssys.domain.IamUser;
import com.tjbank.cssys.repository.*;
import com.tjbank.cssys.web.service.CkOutsourcingCompanyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CkOutsourcingCompanyServiceImpl implements CkOutsourcingCompanyService {
    @Autowired
    private CkOutsourcingCompanyMapper ckOutsourcingCompanyMapper;
    @Autowired
    private IamUserMapper iamUserMapper;
    @Autowired
    private IamGroupMapper iamGroupMapper;
    protected static final Logger logger = LoggerFactory.getLogger(CkOutsourcingCompanyServiceImpl.class);


    @Autowired
    private CkOutsourcingCompanyAcceptLevelMapper levelMapper;
    @Autowired
    private CkOutsourcingCompanyRateMapper rateMapper;

    /**
     * 获取委外公司列表
     * @param params
     * @return
     */
    @Override
    public PageInfo getOutsourcingCompanyList(Map<String, Object> params) {
        logger.info("获取委外公司列表start---参数：param:"+params.toString());
        int page = Integer.parseInt(params.getOrDefault("page", "1").toString());
        int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10").toString());

        String userCode = String.valueOf(params.get("userCode"));
        IamUser iamUser = iamUserMapper.selectByUserCode(userCode);
        String organId = iamUser.getOrganId();
        List<String> organIds = new ArrayList<>();
        organIds.add(organId);
        List<String> organIdList = new ArrayList<>();
        organIdList.add(organId);
        boolean b=true;
        while (b) {
            List<String> strings = iamGroupMapper.selectByParentId(organIdList);
            if (strings.size() == 0) {
                b=false;
            } else {
                organIds.addAll(strings);
                organIdList=strings;
            }
        }
        params.put("organIds",organIds);
        PageHelper.startPage(page, pageSize);
        List<CkOutsourcingCompany> list = ckOutsourcingCompanyMapper.getOutsourcingCompanyList(params);
        PageInfo pageInfo = new PageInfo<>(list);
        logger.info("获取委外公司列表end---result：pageInfo:"+pageInfo.toString());
        return pageInfo;
    }

    /**
     * 添加委外公司
     * @param ckOutsourcingCompany
     */
    @Override
    @Transactional
    public void addOutsourcingCompany(CkOutsourcingCompany ckOutsourcingCompany) {
        logger.info("添加委外公司start---参数：ckOutsourcingCompany:"+ JSON.toJSONString(ckOutsourcingCompany));
        Date date = new Date();
        ckOutsourcingCompany.setUpdateTime(date);
        ckOutsourcingCompanyMapper.insert(ckOutsourcingCompany);
        logger.info("添加委外公司end");
    }

    /**
     * 更新委外公司
     * @param ckOutsourcingCompany
     */
    @Override
    @Transactional
    public void updateOutsourcingCompany(CkOutsourcingCompany ckOutsourcingCompany) {
        logger.info("更新委外公司start---参数：ckOutsourcingCompany:"+JSON.toJSONString(ckOutsourcingCompany));
        Date date = new Date();
        ckOutsourcingCompany.setUpdateTime(date);
        ckOutsourcingCompanyMapper.updateByPrimaryKeySelective(ckOutsourcingCompany);
        logger.info("更新委外公司end");
    }

    @Override
    public Map<String, Object> getCompanyDetails(Integer companyId) {
        Map<String, Object> result = null;
        logger.info("查询委外公司详情信息（含分案等级和对账信息）start---参数：companyId:"+companyId);
        List<Map<String, Object>> companyDetails = ckOutsourcingCompanyMapper.getCompanyDetails(companyId);
        if(!companyDetails.isEmpty()){
            result = companyDetails.get(0);
        }
        logger.info("查询委外公司详情信息（含分案等级和对账信息）end---参数：result:"+result);
        return result;
    }

    @Override
    @Transactional
    public void updateCompanyInfoAndLevelsAndRate(Map<String, Object> params) {
        logger.info("更新委外公司信息和分案逾期等级，以及对账信息 start---参数：ckOutsourcingCompany:"+JSON.toJSONString(params));
        CkOutsourcingCompany ckOutsourcingCompany = JSONObject.parseObject(JSONObject.toJSONString(params), CkOutsourcingCompany.class);

        ckOutsourcingCompanyMapper.updateByPrimaryKeySelective(ckOutsourcingCompany);

        //设置之前的对账信息 逻辑删除，，，is_delete = 2
        Map rateMap = new HashMap<String,Object>();
        rateMap.put("companyId",ckOutsourcingCompany.getId());

        rateMap.put("isDelete","2");
        rateMapper.setDelete(rateMap);
        //将之前的分案逾期等级物理删除
        Map levelMap = new HashMap<String,Object>();
        levelMap.put("companyId",ckOutsourcingCompany.getId());
        levelMapper.deleteByCompanyId(levelMap);

        //插入新的分案等级
        String acceptLevel = String.valueOf(params.get("acceptLevel"));
        if(null!=acceptLevel && !acceptLevel.equals("")){
            String[] split = acceptLevel.split(",");
            List<CkOutsourcingCompanyAcceptLevel> acceptLevels = new ArrayList<>();
            for (String levelName:split) {
                CkOutsourcingCompanyAcceptLevel level = new CkOutsourcingCompanyAcceptLevel();
                level.setCompanyId(ckOutsourcingCompany.getId().intValue());
                level.setLevelName(levelName);
                level.setIsDelete("1");
                acceptLevels.add(level);
            }
            if(acceptLevels.size()>0){
                levelMapper.batchInsert(acceptLevels);
            }
        }

        //添加新的对账信息is_delete = 1
        String backRateList = String.valueOf(params.get("backRates"));

        List<CkOutsourcingCompanyRate> maps = JSONObject.parseArray(backRateList,CkOutsourcingCompanyRate.class);
        List<CkOutsourcingCompanyRate> rates = new ArrayList<CkOutsourcingCompanyRate>();
        if(!maps.isEmpty()){
            for (CkOutsourcingCompanyRate mm : maps) {
                mm.setId(null);
                mm.setCompanyId(ckOutsourcingCompany.getId().intValue());
                mm.setCompanyName(ckOutsourcingCompany.getOutsourcingCompany());
                mm.setCheckModel(ckOutsourcingCompany.getCheckModel());

                mm.setIsDelete("1");
                rates.add(mm);
            }
            if(rates.size()>0){
                rateMapper.batchInsert(rates);
            }
        }



        logger.info("更新委外公司信息和分案逾期等级，以及对账信息 end---参数：ckOutsourcingCompany:"+JSON.toJSONString(params));
    }

}
